package com.accelstack.cmp.controller;

import com.accelstack.cmp.dto.UserCreateRequest;
import com.accelstack.cmp.dto.UserResponse;
import com.accelstack.cmp.entity.User;
import com.accelstack.cmp.enums.UserStatus;
import com.accelstack.cmp.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户管理控制器
 */
@Tag(name = "用户管理", description = "用户的增删改查和AK/SK管理接口")
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {
    
    private final UserService userService;
    
    @Operation(summary = "创建用户", description = "创建新用户并自动生成AK/SK")
    @PostMapping
    public ResponseEntity<UserResponse> create(@Valid @RequestBody UserCreateRequest request) {
        User user = new User();
        user.setUsername(request.getUsername());
        user.setEmail(request.getEmail());
        user.setDescription(request.getDescription());
        user.setStatus(UserStatus.ACTIVE);
        
        User created = userService.create(user);
        
        // 注意：这里返回了SK，实际使用中应该只在创建时返回一次
        UserResponse response = UserResponse.builder()
            .id(created.getId())
            .username(created.getUsername())
            .email(created.getEmail())
            .accessKey(created.getAccessKey())
            .secretKey("请妥善保管，系统不会再次显示")
            .status(created.getStatus())
            .description(created.getDescription())
            .createdAt(created.getCreatedAt())
            .build();
        
        return ResponseEntity.ok(response);
    }
    
    @Operation(summary = "查询用户详情", description = "根据ID查询用户信息（不包含SK）")
    @GetMapping("/{id}")
    public ResponseEntity<UserResponse> getById(
            @Parameter(description = "用户ID", required = true) @PathVariable Long id) {
        return userService.findById(id)
            .map(user -> UserResponse.builder()
                .id(user.getId())
                .username(user.getUsername())
                .email(user.getEmail())
                .accessKey(user.getAccessKey())
                .status(user.getStatus())
                .description(user.getDescription())
                .lastLoginTime(user.getLastLoginTime())
                .lastLoginIp(user.getLastLoginIp())
                .createdAt(user.getCreatedAt())
                .build())
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
    }
    
    @Operation(summary = "分页查询用户", description = "分页查询用户列表")
    @GetMapping
    public ResponseEntity<Page<UserResponse>> getPage(
            @PageableDefault(size = 10, sort = "id") Pageable pageable) {
        
        Page<UserResponse> responsePage = userService.findAll(pageable)
            .map(user -> UserResponse.builder()
                .id(user.getId())
                .username(user.getUsername())
                .email(user.getEmail())
                .accessKey(user.getAccessKey())
                .status(user.getStatus())
                .description(user.getDescription())
                .lastLoginTime(user.getLastLoginTime())
                .lastLoginIp(user.getLastLoginIp())
                .createdAt(user.getCreatedAt())
                .build());
        
        return ResponseEntity.ok(responsePage);
    }
    
    @Operation(summary = "重置用户SK", description = "重置用户的SecretKey，返回新的SK")
    @PostMapping("/{id}/reset-secret-key")
    public ResponseEntity<Map<String, String>> resetSecretKey(
            @Parameter(description = "用户ID", required = true) @PathVariable Long id) {
        
        String newSecretKey = userService.resetSecretKey(id);
        
        Map<String, String> result = new HashMap<>();
        result.put("message", "SecretKey已重置");
        result.put("secretKey", newSecretKey);
        result.put("warning", "请立即保存新的SecretKey，系统不会再次显示");
        
        return ResponseEntity.ok(result);
    }
    
    @Operation(summary = "删除用户", description = "根据ID删除用户")
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(
            @Parameter(description = "用户ID", required = true) @PathVariable Long id) {
        userService.deleteById(id);
        return ResponseEntity.ok().build();
    }
}

